﻿/// <reference path="../app.ts" />

appRoot.factory('authInterceptor', ($rootScope, $q, $location, staticObjects: IStaticObjects) => {
    return {
        request: config => {
            config.headers = config.headers || {};
            if ($rootScope.authData && $rootScope.authData.access_token) {
                config.headers.Authorization = 'Bearer ' + $rootScope.authData.access_token;
            }
            return config;
        },
        response: response => {
            if (response.status === 401) {
                // handle the case where the user is not authenticated
                staticObjects.clearUserInfo();
                if ($location.url() != '/account') {
                    $location.url('/account');
                }
            }
            return response || $q.when(response);
        }
    };
});